<template>
	<view style="height:  750rpx">
		<l-f2 ref="chart"></l-f2>
	</view>
</template>

<script>
	import F2 from '@/uni_modules/lime-f2/components/l-f2/f2-all.min.js';
	export default {
		props:{
			sameAreaProvincePrice:{
				type:Array,
				default(){
					return []
				}
			}
		},
		watch:{
			sameAreaProvincePrice(newVal){
				this.data = newVal.map(item => {
					let json = {};
					json['year'] = item.index
					json['sales'] = Number(item.item)
					return json
				})
			}
		},
		data() {
			return {
				data : []
			}
		},
		mounted() {
			this.$refs.chart.init(config => {
				const chart = new F2.Chart(config);
				chart.source(this.data, {
				sales: {
					tickCount: 5
				}
				});
				chart.tooltip(false);
				chart.interval().position('year*sales').color('l(90) 0:#1890ff 1:#70cdd0');;
				chart.render();

				// 绘制柱状图文本
				const offset = -5;
				const canvas = chart.get('canvas');
				const group = canvas.addGroup();
				const shapes = {};
				this.data.forEach(function(obj) {
					const point = chart.getPosition(obj);
					const text = group.addShape('text', {
						attrs: {
						x: point.x,
						y: point.y + offset,
						text: obj.sales,
						textAlign: 'center',
						textBaseline: 'bottom',
						fill: '#808080'
						}
					});

					shapes[obj.year] = text; // 缓存该 shape, 便于后续查找
				});

				let lastTextShape; // 上一个被选中的 text
				// 配置柱状图点击交互
				chart.interaction('interval-select', {
					selectAxisStyle: {
						fill: '#000',
						fontWeight: 'bold'
					},
					mode: 'range',
					defaultSelected: {
						year: '1962 年',
						sales: 38
					},
					onEnd: function onEnd(ev) {
						const data = ev.data,
						selected = ev.selected;

						lastTextShape && lastTextShape.attr({
							fill: '#808080',
							fontWeight: 'normal'
						});
						if (selected) {
						const textShape = shapes[data.year];
						textShape.attr({
							fill: '#000',
							fontWeight: 'bold'
						});
						lastTextShape = textShape;
						}
						canvas.draw();
					}
				});
				return chart;
			});
		}
	}
</script>